<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMyOrderListAPI, cancelOrderAPI, deleteOrderAPI, confirmReceiptAPI } from '@/apis/order'

const router = useRouter()

// 订单状态翻译
const orderStateMap = {
  1: '待付款',
  2: '待发货',
  3: '待收货',
  4: '待评价',
  5: '已完成',
  6: '已取消'
}

// 订单数据
const orderList = ref([])
const loading = ref(false)
const params = ref({
  page: 1,
  pageSize: 10,
  orderState: 0
})
const total = ref(0)

// 获取订单列表数据
const getOrderList = async () => {
  loading.value = true
  try {
    const res = await getMyOrderListAPI(params.value)
    if (res.data && res.data.code === 200 && res.data.result) {
      orderList.value = res.data.result.items || []
      total.value = res.data.result.total || 0
    } else {
      ElMessage.error('获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表出错:', error)
    ElMessage.error('获取订单列表出错')
  } finally {
    loading.value = false
  }
}

onMounted(() => getOrderList())

// 查看订单详情
const viewOrderDetail = (id) => {
  router.push({
    path: `/member/order/detail/${id}`
  })
}

// 订单操作相关方法
// 取消订单
const cancelOrder = async (id) => {
  try {
    await ElMessageBox.confirm('确认取消该订单吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await cancelOrderAPI(id, '用户取消')
    if (res.data && res.data.code === 200) {
      ElMessage.success('取消订单成功')
      getOrderList()
    } else {
      ElMessage.error('取消订单失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单出错:', error)
      ElMessage.error('取消订单出错')
    }
  }
}

// 删除订单
const deleteOrder = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除该订单吗？删除后不可恢复', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteOrderAPI(id)
    if (res.data && res.data.code === 200) {
      ElMessage.success('删除订单成功')
      getOrderList()
    } else {
      ElMessage.error('删除订单失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除订单出错:', error)
      ElMessage.error('删除订单出错')
    }
  }
}

// 确认收货
const confirmReceipt = async (id) => {
  try {
    await ElMessageBox.confirm('确认收货吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await confirmReceiptAPI(id)
    if (res.data && res.data.code === 200) {
      ElMessage.success('确认收货成功')
      getOrderList()
    } else {
      ElMessage.error('确认收货失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认收货出错:', error)
      ElMessage.error('确认收货出错')
    }
  }
}

// 前往支付
const goPay = (id) => {
  router.push({
    path: '/pay',
    query: { id }
  })
}

// 切换订单状态筛选
const changeTab = (status) => {
  params.value.orderState = status
  params.value.page = 1
  getOrderList()
}

// 分页处理
const handlePageChange = (page) => {
  params.value.page = page
  getOrderList()
}
</script>

<template>
  <div class="order-page">
    <div class="container">
      <div class="order-container">
        <div class="order-header">
          <!-- 切换订单状态的标签卡 -->
          <el-tabs v-model="params.orderState" @tab-click="(tab) => changeTab(tab.index)">
            <el-tab-pane :label="'全部'" name="0" />
            <el-tab-pane :label="'待付款'" name="1" />
            <el-tab-pane :label="'待发货'" name="2" />
            <el-tab-pane :label="'待收货'" name="3" />
            <el-tab-pane :label="'待评价'" name="4" />
            <el-tab-pane :label="'已完成'" name="5" />
            <el-tab-pane :label="'已取消'" name="6" />
          </el-tabs>
        </div>
        
        <div v-if="loading" class="loading">
          <el-skeleton style="width: 100%" :rows="5" animated />
        </div>
        
        <div v-else class="order-list">
          <div v-if="orderList.length === 0" class="empty-order">
            <el-empty description="暂无订单数据" />
          </div>
          
          <div v-else>
            <!-- 订单列表 -->
            <div v-for="order in orderList" :key="order.id" class="order-item">
              <div class="order-header">
                <p>订单编号：{{ order.id }}</p>
                <p>下单时间：{{ order.createTime }}</p>
                <p class="state">{{ orderStateMap[order.state] }}</p>
              </div>
              
              <!-- 订单商品 -->
              <div class="order-goods" @click="viewOrderDetail(order.id)">
                <div class="goods-item" v-for="(item, index) in order.orderItems" :key="index">
                  <img :src="item.image" alt="商品图片">
                  <div class="goods-info">
                    <p class="goods-name">{{ item.name }}</p>
                    <p class="attrs">{{ item.attrsText }}</p>
                  </div>
                  <div class="goods-price">
                    <p>¥{{ item.realPay }}</p>
                    <p>x{{ item.quantity }}</p>
                  </div>
                </div>
              </div>
              
              <!-- 订单金额和操作 -->
              <div class="order-footer">
                <div class="order-amount">
                  <p>共 {{ order.totalNum || 0 }} 件商品</p>
                  <p class="amount">实付：<span class="price">¥{{ order.payMoney || 0 }}</span></p>
                </div>
                
                <div class="order-actions">
                  <!-- 根据订单状态显示不同按钮 -->
                  <!-- 待付款 -->
                  <template v-if="order.state === 1">
                    <el-button size="small" type="primary" @click="goPay(order.id)">去支付</el-button>
                    <el-button size="small" @click="cancelOrder(order.id)">取消订单</el-button>
                  </template>
                  
                  <!-- 待发货 -->
                  <template v-if="order.state === 2">
                    <el-button size="small" @click="viewOrderDetail(order.id)">查看详情</el-button>
                  </template>
                  
                  <!-- 待收货 -->
                  <template v-if="order.state === 3">
                    <el-button size="small" type="primary" @click="confirmReceipt(order.id)">确认收货</el-button>
                    <el-button size="small" @click="viewOrderDetail(order.id)">查看详情</el-button>
                  </template>
                  
                  <!-- 待评价 -->
                  <template v-if="order.state === 4">
                    <el-button size="small" type="primary" @click="viewOrderDetail(order.id)">去评价</el-button>
                    <el-button size="small" @click="deleteOrder(order.id)">删除订单</el-button>
                  </template>
                  
                  <!-- 已完成 -->
                  <template v-if="order.state === 5">
                    <el-button size="small" @click="viewOrderDetail(order.id)">查看详情</el-button>
                    <el-button size="small" @click="deleteOrder(order.id)">删除订单</el-button>
                  </template>
                  
                  <!-- 已取消 -->
                  <template v-if="order.state === 6">
                    <el-button size="small" @click="deleteOrder(order.id)">删除订单</el-button>
                  </template>
                </div>
              </div>
            </div>
            
            <!-- 分页 -->
            <div class="pagination">
              <el-pagination
                background
                layout="prev, pager, next"
                :total="total"
                :page-size="params.pageSize"
                :current-page="params.page"
                @current-change="handlePageChange"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.order-page {
  padding: 20px 0;
  background-color: #f5f5f5;
  
  .container {
    width: 1240px;
    margin: 0 auto;
  }
  
  .order-container {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    
    .order-header {
      border-bottom: 1px solid #f5f5f5;
      padding-bottom: 10px;
    }
    
    .loading {
      padding: 20px 0;
    }
    
    .empty-order {
      padding: 50px 0;
      display: flex;
      justify-content: center;
    }
    
    .order-item {
      margin-top: 20px;
      padding: 20px;
      border-radius: 4px;
      border: 1px solid #e4e4e4;
      
      .order-header {
        display: flex;
        justify-content: space-between;
        padding-bottom: 10px;
        border-bottom: 1px solid #f5f5f5;
        font-size: 14px;
        color: #999;
        
        .state {
          color: var(--primary-color);
          font-weight: 500;
        }
      }
      
      .order-goods {
        padding: 20px 0;
        cursor: pointer;
        
        .goods-item {
          display: flex;
          margin-bottom: 10px;
          
          img {
            width: 80px;
            height: 80px;
            object-fit: cover;
          }
          
          .goods-info {
            flex: 1;
            padding: 0 10px;
            
            .goods-name {
              font-size: 14px;
              margin-bottom: 5px;
            }
            
            .attrs {
              font-size: 12px;
              color: #999;
            }
          }
          
          .goods-price {
            width: 100px;
            text-align: right;
            font-size: 14px;
            
            p:nth-child(2) {
              color: #999;
            }
          }
        }
      }
      
      .order-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 10px;
        border-top: 1px solid #f5f5f5;
        
        .order-amount {
          font-size: 14px;
          
          .amount {
            margin-top: 5px;
            
            .price {
              font-size: 18px;
              color: var(--price-color);
              font-weight: 500;
            }
          }
        }
        
        .order-actions {
          .el-button + .el-button {
            margin-left: 10px;
          }
        }
      }
    }
    
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}
</style> 